// stores/websocket.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'

interface WebSocketConnection {
  key: string
  instance: WebSocket
  reconnectCount: number
  isManualClose: boolean
  onMessage: (event: MessageEvent) => void
  reconnectTimer?: ReturnType<typeof setTimeout>  // 重连计时器
}

export const useWebSocketStore = defineStore('websocket', () => {
  const connections = ref<Map<string, WebSocketConnection>>(new Map())

  // 创建 WebSocket 连接（带自动重连保护）
  const createConnection = (
    key: string,
    url: string,
    onMessage: (event: MessageEvent) => void
  ) => {
    // 清理旧连接
    const cleanupConnection = (key: string) => {
      const connection = connections.value.get(key)
      if (connection) {
        // 清除未执行的自动重连
        if (connection.reconnectTimer) {
          clearTimeout(connection.reconnectTimer)
        }
        connection.instance.onclose = null
        connection.instance.close()
        connections.value.delete(key)
      }
    }

    // 存在相同 key 时先彻底清理
    if (connections.value.has(key)) {
      cleanupConnection(key)
    }

    const ws = new WebSocket(url)

    const connection: WebSocketConnection = {
      key,
      instance: ws,
      reconnectCount: 0,
      isManualClose: false,
      onMessage
    }

    // 绑定事件（带连接状态跟踪）
    ws.onopen = () => {
      console.log(`[WebSocket] 连接成功 | key: ${key}`)
      connection.reconnectCount = 0
      connection.isManualClose = false
    }

    ws.onmessage = onMessage

    ws.onclose = (event) => {
      // 手动关闭时跳过重连
      if (connection.isManualClose) {
        console.log(`[WebSocket] 手动关闭 | key: ${key}`)
        return
      }

      console.log(`[WebSocket] 连接关闭 | key: ${key}，代码: ${event.code}，原因: ${event.reason}`)

      // 指数退避重连策略
      if (connection.reconnectCount < 5) {
        const delay = Math.min(3000 * Math.pow(2, connection.reconnectCount), 30000)  // 最大30秒
        console.log(`[WebSocket] ${delay}ms后重试 (${connection.reconnectCount + 1}/5) | key: ${key}`)

        connection.reconnectTimer = setTimeout(() => {
          connection.reconnectCount++
          createConnection(key, url, onMessage)
        }, delay)
      } else {
        console.error(`[WebSocket] 达到最大重连次数，停止重连 | key: ${key}`)
      }
    }

    ws.onerror = (error) => {
      console.error(`[WebSocket] 连接错误 | key: ${key}`, error)
    }

    connections.value.set(key, connection)
  }

  // 安全关闭连接
  const closeConnection = (key: string) => {
    const connection = connections.value.get(key)
    if (connection) {
      // 标记为手动关闭
      connection.isManualClose = true

      // 清理待处理的重连
      if (connection.reconnectTimer) {
        clearTimeout(connection.reconnectTimer)
      }

      // 关闭连接
      // @ts-ignore
      if ([WebSocket.OPEN, WebSocket.CONNECTING].includes(connection.instance.readyState)) {
        connection.instance.close()
      }

      connections.value.delete(key)
      console.log(`[WebSocket] 连接已关闭 | key: ${key}`)
    }
  }

  // 发送消息
  const sendMessage = (key: string, message: string) => {
    const connection = connections.value.get(key)
    if (connection && connection.instance.readyState === WebSocket.OPEN) {
      connection.instance.send(message)
    } else {
      console.error(`[WebSocket] 连接未就绪 | key: ${key}`)
    }
  }

  // 获取连接状态
  const getConnectionState = (key: string) => {
    const connection = connections.value.get(key)
    return connection ? connection.instance.readyState : WebSocket.CLOSED
  }

  return {
    connections,
    createConnection,
    closeConnection,
    sendMessage,
    getConnectionState
  }
})
